package com.atguigu.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.constant.RedisConst;
import com.atguigu.entity.UserInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.UserInfoService;
import com.atguigu.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserInfoService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public RetVal login(@RequestBody UserInfo uiUser, HttpServletRequest request){
        //a.根据用户账号密码从数据库中查询用户信息
        UserInfo dbUser=userService.queryUserFromDb(uiUser);
        if(dbUser!=null){
            //b.生成一个token/用户昵称信息返回给页面设置到cookie
            String token = UUID.randomUUID().toString();
            Map<String, Object> retValMap = new HashMap<>();
            retValMap.put("token",token);
            //用户昵称信息
            retValMap.put("nickName",dbUser.getLoginName());
            /**
             * c.将用户信息存储到redis中
             *  用户信息的key
             *  存储的用户信息
             *      用户的id
             *      用户登录的ip地址 用于判断是否为同一台电脑登录
             */
            JSONObject loginInfo = new JSONObject();
            loginInfo.put("userId",dbUser.getId());
            loginInfo.put("loginIp", IpUtil.getIpAddress(request));
            String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+token;
            redisTemplate.opsForValue().set(userKey,loginInfo.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return RetVal.ok(retValMap);
        }else{
            return RetVal.fail().message("登录失败");
        }
    }

    //2.退出登录
    @GetMapping("logout")
    public RetVal login(HttpServletRequest request){
        //得到token有两种方式 a.cookie中拿相对来说要麻烦一些 b.从header中拿
        String userKey= RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token");
        redisTemplate.delete(userKey);
        return RetVal.ok();
    }

}
